
package com.ims.common.email;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URL;
import java.util.HashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class EmailServices {

	private static final Log LOG = LogFactory.getLog(EmailServices.class);

	freemarker.template.Configuration conf = null;
	private static final String DEFAULT_TEMPLATE_DIR = "/template";
	private String templateDir = null;

	/**
	 * executes freemarker engine to generate Email content based 
	 * template and data based on HashMap. 
	 */
	public String createEmailUsingTemplate(String templateName,
			HashMap<String, Object> paramMap) {
		String writerStringEmailText = "";
		try {
			writerStringEmailText = process(templateName, paramMap);
		} catch (Exception ex) {
			LOG.error("Error occured while creation of email template:" , ex);
	
		}
		return writerStringEmailText;
	}

	/**
	 * The core process logic for generating dynamic content for email template.
	 * @param templateName
	 * @param paramMap
	 * @return
	 * @throws CustomException
	 */
	public String process(String templateName, HashMap<String, Object> paramMap)
			 {
		// find the right template
		// Can also use API: conf.setDirectoryForTemplateLoading("/template");		
		StringWriter out = new StringWriter();
		freemarker.template.Template template_ = null;
		conf = new freemarker.template.Configuration();

		try {
		     			
			setTemplateDirectory(DEFAULT_TEMPLATE_DIR);
			template_ = conf.getTemplate(templateName);
			template_.process(paramMap, out);
			LOG.debug("template output is :" + out);
		} catch (Exception ex) {
			out = new StringWriter();
			LOG.error("Error occured while creation of template:" , ex);
		}
		return out.toString();
	}


	/**
	 * Set the directory to load email templates
	 * @param dirname
	 * @throws IOException
	 */
	public void setTemplateDirectory(String dirname) throws IOException {
		URL url = getClass().getResource("EmailServices.class");
		File parent = new File(url.getFile()).getParentFile();
		File dir = new File(parent, dirname);
		conf.setDirectoryForTemplateLoading(dir);
		LOG.info("Setting loading directory as: " + dir);
	}

	public String getTemplateDir() {
		return templateDir;
	}

	public void setTemplateDir(String templateDir) {
		this.templateDir = templateDir;
	}
	
}
